import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutterapp2/base/request/request.dart';
import 'package:flutterapp2/base/visibile_ext.dart';
import 'package:flutterapp2/building/buildinfo.dart';
import 'package:flutterapp2/model/base_response.dart';
import 'package:flutterapp2/base/request/base_request_page.dart';
import 'package:flutterapp2/test/seconde_page.dart';
import 'package:flutterapp2/util/navigator_util.dart';
import 'package:provider/provider.dart';

class TestRequestPage extends StatefulWidget {
  @override
  _TestRequestPageState createState() => _TestRequestPageState();
}

class _TestRequestPageState extends State<TestRequestPage> {
  GlobalKey _globalKey;
  BuildInfo buildInfo;

  @override
  void initState() {
    super.initState();
    _globalKey = GlobalKey();
  }

  _updateTitle() {
    /// 所在的widget第一帧绘制完成之后回调，第一帧绘制完成标志着已经Build完成
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      debugPrint(" >> addPostFrameCallback}");
      _globalKey.currentState.setState(() {});
    });
  }

//  GlobalKey globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    print(">> build");
    return Scaffold(
      /*key: globalKey,*/
      appBar: AppBar(
        title: StatefulBuilder(
            key: _globalKey,
            builder: (context, setState) => Text(buildInfo?.name ?? "")),
      ),
      body: BaseRequestPage<BaseResponse>(
        request: mockNetworkData,
//        requestStateWork: CommonRequestStateWork(retryText: "点击重试吧~"),
        resultChecker: (data) => data?.hasData() == true,
        builder: _buildContent,
      ),
    );
  }

  Widget _buildContent(
      BuildContext context, BaseResponse data, RetryFunction refreshFunction) {
    buildInfo = BuildInfo.fromJson(jsonDecode(data.data));
    _updateTitle();
    print(">> _buildContent ${buildInfo.id}");
    return ChangeNotifierProvider.value(
        value: buildInfo,
        child: VisibilityExt(
          visible: buildInfo != null,
          builder: () => Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text("id=${buildInfo.id},name=${buildInfo.name}"),
              RaisedButton(
                  onPressed: () {
                        NavigatorUtil.push(context, SecondPage(), (result) {
                          print(">> onResult => $result");
                          refreshFunction();
                        });
                  },
                  child: Text("reload data"))
            ],
          ),
        ));
  }

  /// 模拟网络请求
  Future<BaseResponse> mockNetworkData() async {
    if (Random().nextInt(2) == 1) {
      return Future.error("模拟异常");
    }

    var buildInfo = BuildInfo(id: Random().nextInt(100).toString(), name: "张三");
    print(">> mockNetworkData ${buildInfo.id}");
    return Future.delayed(Duration(seconds: 1), () {
      return BaseResponse(errno: 0, data: jsonEncode(buildInfo));
    });
  }
}
